import { DataTypes, Model, Sequelize } from "sequelize";
import { User } from "./User";

/**
 * 用户会话模型接口
 */
export interface UserSessionAttributes {
  id?: number;
  session_id: string;
  user_id: number;
  session_data?: string;
  ip_address: string;
  user_agent?: string;
  expires_at: Date;
  is_active?: number;
  created_at?: Date;
  updated_at?: Date;
}

/**
 * 用户会话模型类
 */
export class UserSession extends Model<UserSessionAttributes> implements UserSessionAttributes {
  public id!: number;
  public session_id!: string;
  public user_id!: number;
  public session_data!: string;
  public ip_address!: string;
  public user_agent!: string;
  public expires_at!: Date;
  public is_active!: number;
  public created_at!: Date;
  public updated_at!: Date;
}

/**
 * 初始化用户会话模型
 */
export function initUserSessionModel(sequelize: Sequelize): typeof UserSession {
  UserSession.init(
    {
      id: {
        type: DataTypes.BIGINT,
        primaryKey: true,
        autoIncrement: true,
        comment: "会话ID，主键自增"
      },
      session_id: {
        type: DataTypes.STRING(128),
        allowNull: false,
        unique: true,
        comment: "会话标识符，唯一索引"
      },
      user_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        comment: "关联用户ID",
        references: {
          model: "users",
          key: "id"
        },
        onDelete: "CASCADE"
      },
      session_data: {
        type: DataTypes.TEXT,
        allowNull: true,
        comment: "会话数据，JSON格式存储"
      },
      ip_address: {
        type: DataTypes.STRING(45),
        allowNull: false,
        comment: "登录IP地址"
      },
      user_agent: {
        type: DataTypes.TEXT,
        allowNull: true,
        comment: "用户代理信息（浏览器、设备等）"
      },
      expires_at: {
        type: DataTypes.DATE,
        allowNull: false,
        comment: "会话过期时间"
      },
      is_active: {
        type: DataTypes.TINYINT,
        defaultValue: 1,
        comment: "会话状态：1-活跃，0-已失效"
      },
      created_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        comment: "创建时间"
      },
      updated_at: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        comment: "更新时间"
      }
    },
    {
      sequelize,
      tableName: "user_sessions",
      modelName: "UserSession",
      timestamps: true,
      underscored: true,
      indexes: [
        {
          fields: ["session_id"],
          name: "idx_session_id"
        },
        {
          fields: ["user_id"],
          name: "idx_user_id"
        },
        {
          fields: ["expires_at"],
          name: "idx_expires_at"
        },
        {
          fields: ["is_active"],
          name: "idx_is_active"
        }
      ],
      comment: "用户会话管理表"
    }
  );

  return UserSession;
}

/**
 * 定义模型关联关系
 */
export function defineUserSessionAssociations(): void {
  // 用户会话属于用户
  UserSession.belongsTo(User, {
    foreignKey: "user_id",
    as: "user"
  });

  // 用户有多个会话
  User.hasMany(UserSession, {
    foreignKey: "user_id",
    as: "sessions"
  });
}
